package moveresize;

import java.awt.Component;
import java.awt.Rectangle;
import java.awt.event.ComponentAdapter;
import java.awt.event.ComponentEvent;
import java.awt.event.ComponentListener;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.util.LinkedList;
import java.util.List;
import java.util.concurrent.atomic.AtomicBoolean;

import javax.swing.JComponent;


public class BoundsHistory {
	private final JComponent component;
    private AtomicBoolean attached;
	
	public BoundsHistory(JComponent control) {
		this.component = control;
        attached = new AtomicBoolean(false);
	}
	
	private ComponentListener componentListener = new ComponentAdapter() {

		public void componentMoved(ComponentEvent e) {
			if (!Resizer.isResizing(component)) {
				pushBounds(component.getBounds());
			}
		}

		public void componentResized(ComponentEvent e) {
			if (!Resizer.isResizing(component)) {
				pushBounds(component.getBounds());
			}
		}
	};

	private KeyListener keyListener = new KeyAdapter() {

		public void keyReleased(KeyEvent e) {
			Component control = getComponent();

			if (e.getKeyChar() == 'z') {
				try {
		        	control.removeComponentListener(componentListener);
					backward();
				} finally {
		        	control.addComponentListener(componentListener);
				}
			} else if (e.getKeyChar() == 'y') {
				try {
		        	control.removeComponentListener(componentListener);
					forward();
				} finally {
		        	control.addComponentListener(componentListener);
				}
			}
		}
		
	};
	
	public JComponent getComponent() {
		return component;
	}
	
	public void attach() {
        if (attached.compareAndSet(false, true)) {
        	component.addComponentListener(componentListener);
    		component.addKeyListener(keyListener);
    		pushBounds(component.getBounds());
        }
	}

	public void dettach() {
        if (attached.compareAndSet(true, false)) {
        	component.removeComponentListener(componentListener);
        	component.removeKeyListener(keyListener);
        }
	}
	
	private List<Rectangle> boundsHistory = new LinkedList<Rectangle>();
	private int historyIndex = -1;
	
	private void pushBounds(Rectangle bounds) {
		if (historyIndex >= 0) {
			while (historyIndex < boundsHistory.size() - 1) {
				boundsHistory.remove(boundsHistory.size() - 1);
			}
		}
		boundsHistory.add(bounds);
		historyIndex = boundsHistory.size() -1;
	}

	private void backward() {
		if (historyIndex <= 0) {
			return;
		}
		historyIndex--;
		Rectangle bounds = boundsHistory.get(historyIndex);
		component.setBounds(bounds);
	}
	
	private void forward() {
		if (historyIndex >= (boundsHistory.size() -1)) {
			return;
		}
		historyIndex++;
		Rectangle bounds = boundsHistory.get(historyIndex);
		component.setBounds(bounds);
	}

}
